package socket.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * TCP 客户端
 */
public class TCPDictClient {
    //建立连接
    public Socket socket = null;

    public TCPDictClient(String serverIp, int serverPort) throws IOException {
        //如果服务端没有启动, 连接是建立不成功的
        socket = new Socket(serverIp,serverPort);//和服务端建立连接
    }

    public void start(){
        System.out.println("和服务端建立连接....");
        try(OutputStream outputStream = socket.getOutputStream()) {
            try(InputStream inputStream = socket.getInputStream()){
                PrintWriter writer = new PrintWriter(outputStream);
                //发送数据
                Scanner scanner = new Scanner(System.in);//此行代码, 是为了从控制台拿到数据
                while (true){
                    System.out.println("请输入发送的数据:");
                    String request = scanner.nextLine();//从控制台输入发送的数据
                    writer.println(request);
                    writer.flush();

                    //接收响应
                    Scanner responseScanner = new Scanner(inputStream);
                    String response = responseScanner.nextLine();
                    System.out.printf("发送数据:%s,接收到响应数据:%s\n",request,response);
                }
            }



        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPDictClient client = new TCPDictClient("127.0.0.1",9090);
        client.start();
    }
}
